﻿function __lightBox($, lightBoxName) {
    var lightBoxSuffix = lightBoxName ? '-' + lightBoxName : '';
    if (!lightBoxName) lightBoxName = 'lightBox';
    var suffixToken = /{suffix}/g;
    function getID(id) {
        return id + lightBoxSuffix;
    }
    var lightBoxCloseName = lightBoxName + 'Close';
    lightBoxCount = 0;
    if (!window.__lightBoxIDs) window.__lightBoxIDs = [];

    var cachedRequestContents = {};
    var lightBoxGlobalHandlers = [];

    function raiseEvent(e) {
        if (typeof (e) == 'string') return raiseEvent({ type: e });
        for (var i = 0; i < lightBoxGlobalHandlers.length; i++) {
            lightBoxGlobalHandlers[i](e);
        }
    }

    $[lightBoxName] = window['$' + lightBoxName] = function (selector, settings, event) {
        if (window.top != self && window.top.jQuery && window.top.jQuery.lightBox) return window.top.jQuery.lightBox.apply(this, arguments);
        if (selector instanceof Function) {
            lightBoxGlobalHandlers.push(selector);
            return;
        }
        if (typeof settings == 'string') settings = window[settings];
        if (window.lightBoxSettings) {
            var copy = jQuery.extend({}, window.lightBoxSettings);
            settings = jQuery.extend(copy, settings);
        }
        else {
            settings = settings || {};
        }

        settings = jQuery.extend({
            minWidth: 300,
            minHeight: 200,
            overlayBgColor: "#000",
            overlayOpacity: 0.8,
            fixedNavigation: false,
            imageLoading: "images/lightbox-ico-loading.gif",
            imageBtnPrev: "images/lightbox-btn-prev.gif",
            imageBtnNext: "images/lightbox-btn-next.gif",
            imageBtnClose: "images/lightbox-btn-close.gif",
            imageBlank: "images/lightbox-blank.gif",
            imageError: "images/lightbox-error.gif",
            containerBorderSize: 10,
            containerResizeSpeed: 400,
            txtImage: "Image",
            txtOf: "of",
            keyToClose: "c",
            keyToPrev: "p",
            keyToNext: "n",
            imageArray: [],
            shortcutDisabled: false,
            activeImage: 0,
            top: 0,
            callback: null,
            context: null
        }, settings);
        var jQueryMatchedObj = this;
        var objects = {
            container: null,
            overlay: null,
            mainBox: null,
            imageBox: null,
            imageContainer: null,
            contents: null,
            image: null,
            navigator: null,
            btnPrev: null,
            btnNext: null,
            loading: null,
            link: null,
            dataBox: null,
            imageData: null,
            details: null,
            caption: null,
            current: null,
            secNavigator: null,
            btnClose: null
        };
        var finishHandlers = [];
        var loadCompleted = false;
        var activeObject = null;

        function _initialize(nodes, context) {
            if (!nodes) return;
            if (!nodes[0] && (nodes instanceof jQuery && nodes.size() <= 0)) {
                return;
            }

            _start($(context || nodes[0] || nodes.get(0)), nodes);
            return false;
        }
        function _start(objClicked, jQueryMatchedObj) {
            activeObject = objClicked;
            $("embed, object, select").css({
                visibility: "hidden"
            });
            _set_interface();
            settings.imageArray.length = 0;
            settings.activeImage = 0;
            if (jQueryMatchedObj.size() == 1) {
                settings.imageArray.push({
                    tag: $(objClicked),
                    href: $(objClicked).attr("href"),
                    title: $(objClicked).attr("title"),
                    width: $(objClicked).attr("lightbox-width") || settings.width,
                    height: $(objClicked).attr("lightbox-height") || settings.height
                });
            }
            else {
                jQueryMatchedObj.each(function () {
                    settings.imageArray.push({
                        tag: $(this),
                        href: $(this).attr("href"),
                        title: $(this).attr("title"),
                        width: $(this).attr("lightbox-width"),
                        height: $(this).attr("lightbox-height")
                    });
                });
            }
            while (settings.imageArray[settings.activeImage].href != $(objClicked).attr("href")) {
                settings.activeImage++;
            }
            _set_image_to_view();
        }
        function _set_interface() {
            objects.container = $('<div><div id="jquery-overlay" class="jquery-overlay"></div><div id="jquery-lightbox" class="jquery-lightbox"><div id="lightbox-container-image-box" class="lightbox-container-image-box"><div id="lightbox-container-image" class="lightbox-container-image"><div id="lightbox-contents" class="lightbox-contents" onclick="event.cancelBubble = true;"></div><img id="lightbox-image" class="lightbox-image"><div style="" id="lightbox-nav" class="lightbox-nav"><a href="javascript:;" id="lightbox-nav-btnPrev" class="lightbox-nav-btnPrev"></a><a href="#" id="lightbox-nav-btnNext" class="lightbox-nav-btnNext"></a></div><div id="lightbox-loading" class="lightbox-loading"><a href="javascript:;" id="lightbox-loading-link" class="lightbox-loading-link"><img src="' + settings.imageLoading + '"></a></div></div></div><div id="lightbox-container-image-data-box" class="lightbox-container-image-data-box"><div id="lightbox-container-image-data" class="lightbox-container-image-data"><div id="lightbox-image-details" class="lightbox-image-details"><span id="lightbox-image-details-caption" class="lightbox-image-details-caption"></span><span id="lightbox-image-details-currentNumber" class="lightbox-image-details-currentNumber"></span></div><div id="lightbox-secNav" class="lightbox-secNav"><a href="#" id="lightbox-secNav-btnClose" class="lightbox-secNav-btnClose"><img src="' + settings.imageBtnClose + '"></a></div></div></div></div></div>');

            objects.overlay = $('#jquery-overlay', objects.container);
            objects.mainBox = $('#jquery-lightbox', objects.container);

            objects.overlay.css('z-index', (parseInt(objects.overlay.css('z-index')) || 100) + lightBoxCount);
            objects.mainBox.css('z-index', parseInt(objects.overlay.css('z-index')) + 1);

            objects.imageBox = $('#lightbox-container-image-box', objects.container);
            objects.imageContainer = $('#lightbox-container-image', objects.container);
            objects.contents = $('#lightbox-contents', objects.container);
            objects.image = $('#lightbox-image', objects.container);
            objects.navigator = $('#lightbox-nav', objects.container);
            objects.btnPrev = $('#lightbox-nav-btnPrev', objects.container);
            objects.btnNext = $('#lightbox-nav-btnNext', objects.container);
            objects.loading = $('#lightbox-loading', objects.container);
            objects.link = $('#lightbox-loading-link', objects.container);
            objects.dataBox = $('#lightbox-container-image-data-box', objects.container);
            objects.imageData = $('#lightbox-container-image-data', objects.container);
            objects.details = $('#lightbox-image-details', objects.container);
            objects.caption = $('#lightbox-image-details-caption', objects.container);
            objects.current = $('#lightbox-image-details-currentNumber', objects.container);
            objects.secNavigator = $('#lightbox-secNav', objects.container);
            objects.btnClose = $('#lightbox-secNav-btnClose', objects.container);

            $("body").append(objects.container);
            lightBoxCount++;

            var arrPageSizes = ___getPageSize();
            objects.overlay.css({
                backgroundColor: settings.overlayBgColor,
                opacity: settings.overlayOpacity,
                width: arrPageSizes[0],
                height: arrPageSizes[1]
            }).fadeIn();
            var arrPageScroll = ___getPageScroll();
            objects.mainBox.css({
                top: Math.max(settings.top, arrPageScroll[1] + (arrPageSizes[3] / 10)),
                left: arrPageScroll[0]
            }).show();
            objects.overlay.add(objects.mainBox).click(function () {
                _finish();
            });
            objects.link.add(objects.btnClose).click(function () {
                _finish();
                return false;
            });

            $(window).resize(function () {
                var arrPageSizes = ___getPageSize();
                objects.overlay.css({
                    width: arrPageSizes[0],
                    height: arrPageSizes[1]
                });
                var arrPageScroll = ___getPageScroll();
                objects.mainBox.css({
                    top: arrPageScroll[1] + (arrPageSizes[3] / 10),
                    left: arrPageScroll[0]
                });
            });
            raiseEvent('open');
        }

        _unregisterClose = null;

        function _registerClose() {
            var previous = window[lightBoxCloseName];
            window[lightBoxCloseName] = function () {
                if (!loadCompleted) return window.setTimeout(arguments.callee, 200);
                _finish();
            };

            _unregisterClose = function () {
                window[lightBoxCloseName] = previous;
                lightBoxCount--;
                raiseEvent('close');
                if (!lightBoxCount) raiseEvent('close-all');
            };
        }

        function _set_image_to_view() {

            objects.loading.show();

            if (settings.fixedNavigation) {
                objects.image.add(objects.dataBox).add(objects.current).hide();
                //$("#lightbox-image{suffix},#lightbox-container-image-data-box{suffix},#lightbox-image-details-currentNumber{suffix}".replace(suffixToken, lightBoxSuffix)).hide();
            }
            else {
                objects.image.add(objects.navigator).add(objects.btnPrev).add(objects.btnNext).add(objects.dataBox).add(objects.current).hide();
                //$("#lightbox-image{suffix},#lightbox-nav{suffix},#lightbox-nav-btnPrev{suffix},#lightbox-nav-btnNext{suffix},#lightbox-container-image-data-box{suffix},#lightbox-image-details-currentNumber{suffix}".replace(suffixToken, lightBoxSuffix)).hide();
            }


            _registerClose();

            var objImagePreloader = new Image();
            var imageData = settings.imageArray[settings.activeImage];
            var source = imageData.href;
            var sourceType = /^((?:(?:ajax-)?(?:text|html))|json|iframe|element):/.exec(source);

            var boxWidth = imageData.width || settings.boxWidth || 600;
            var boxHeight = imageData.height || settings.boxHeight || 'auto';

            var autoSize = false;
            if (sourceType) {
                sourceType = sourceType[1];
                source = source.substr(sourceType.length + 1);
            }

            if (sourceType == 'element') {
                var targetTag = $(source, $(activeObject).get(0).ownerDocument);
                var next = targetTag.get(0).nextSibling;
                var parent = targetTag.get(0).parentNode;
                var previousDisplayValue = targetTag.css('display');
                var previousVisibility = targetTag.css('visibility');
                var previousPosition = targetTag.css('position');
                objects.contents.append(targetTag);
                targetTag.show();
                if (isNaN(boxWidth)) {
                    boxWidth = targetTag.outerWidth();
                }
                if (isNaN(boxHeight)) {
                    targetTag.css('visibility', 'visible');
                    targetTag.css('position', 'absolute');
                    boxHeight = targetTag.outerHeight();
                    targetTag.css('visibility', previousVisibility);
                    targetTag.css('position', previousPosition);
                }
                finishHandlers.push(function () {
                    if (next)
                        $(next).before(targetTag);
                    else
                        targetTag.appendTo(parent);
                    targetTag.css('display', previousDisplayValue);
                });
                sourceType = 'none';
            }
            else {
                if (!isNaN(boxWidth)) boxWidth = parseInt(boxWidth);
                if (!isNaN(boxHeight)) boxHeight = parseInt(boxHeight);
            }

            var loadingHandle = function (source, type) {
                var contents = objects.contents;
                switch (type) {
                    case 'iframe':
                        source = $(source).get(0);
                        contents.height(boxHeight);
                        contents.width(boxWidth);
                        contents.empty().append(source);
                        $(source).bind('load', function () {
                            var win = source.contentWindow;
                            var doc = win.document;
                            $(source).css('visibility', 'visible');
                            _resize_container_image_box(contents.outerWidth(), (doc.documentElement || doc.body).scrollHeight);
                        });
                        _resize_container_image_box(contents.outerWidth(), contents.outerHeight() || 100);
                        break;
                    case 'text':
                    case 'html':
                        if (type == 'text') {
                            contents.html('<pre>' + source + '</pre>');
                        }
                        else {
                            contents.html(source);
                        }
                        contents.height(boxHeight);
                        contents.width(boxWidth);
                        _resize_container_image_box(contents.outerWidth(), contents.outerHeight() || 100);
                        break;
                    case 'none':
                        contents.height(boxHeight);
                        contents.width(boxWidth);
                        _resize_container_image_box(contents.outerWidth(), contents.outerHeight() || 100);
                        break;
                    default:
                        objects.image.attr("src", source);
                        var width = Math.max(objImagePreloader.width, settings.minWidth);
                        //var height = Math.max(objImagePreloader.height, settings.minHeight);
                        objects.image.width(width); //.height(height);
                        _resize_container_image_box(width, objects.image.height());
                        break;
                }
                loadCompleted = true;
                objImagePreloader.onload = objImagePreloader.onerror = function () {
                };
            };

            if (sourceType) {
                objects.contents.show();
                settings.hideImage = true;
            }
            else {
                objects.contents.hide();
                settings.hideImage = false;
            }

            if (typeof (settings.hideNavigator) == 'undefined') settings.hideNavigator = sourceType && settings.imageArray.length == 1;
            if (sourceType == 'ajax-html' || sourceType == 'ajax-text') {

                $.ajax({
                    url: source,
                    complete: function (data) {
                        if (sourceType == 'ajax-html')
                            loadingHandle(data.responseText, 'html');
                        else
                            loadingHandle(data.responseText, 'text');
                    }
                });
            }
            else if (sourceType == 'html' || sourceType == 'text') {
                if (!source) source = $(imageData.tag).attr('lightbox-' + sourceType) || '';
                loadingHandle(source, sourceType);
            }
            else if (sourceType == 'iframe') {
                var frameID = 'lightbox-iframe-' + new Date().getTime();
                loadingHandle($('<iframe id="' + frameID + '" frameborder="no" scrolling="no" src="' + source + '" style="width: ' + boxWidth + '; height: ' + boxHeight + '; visibility: hidden"></iframe>'), 'iframe');
                var frame = $('#' + frameID).get(0);
                if (frame.__lightBoxClosed) frame.__lightBoxClosed = false;
                frame.lightBoxCallback = function () {
                    if (settings.callback) {
                        settings.callback.apply(settings.context, arguments);
                    }
                    //                    frame.__lightBoxDispose = _disposeElements;
                    lightBoxClose();
                    if (!$(frame).attr('lightbox-preversed')) $(frame).remove();
                    _disposeElements();
                    //                    frame.__lightBoxClosed = true;
                };
            }
            else if (sourceType == 'none') {
                loadingHandle(null, sourceType);
            }
            else {
                objImagePreloader.onload = function () {
                    loadingHandle(source, sourceType);
                };

                objImagePreloader.onerror = function () {
                    this.src = settings.imageError;
                    this.onload = function () {
                        loadingHandle(this.src, sourceType);
                    };
                };
                objImagePreloader.src = sourceType ? settings.imageBlank : imageData.href;
            }

            if (settings.hideNavigator) {
                objects.btnNext.hide();
                objects.btnPrev.hide();
                //objects.navigator.hide();
                //objects.container.addClass('lightbox-option-hide-navigator');
            }
            else {
                //objects.container.removeClass('lightbox-option-hide-navigator');
            }
        }
        function _resize_container_image_box(intImageWidth, intImageHeight) {
            var intCurrentWidth = objects.imageBox.width();
            var intCurrentHeight = objects.imageBox.height();
            var intWidth = (intImageWidth + (settings.containerBorderSize * 2));
            var intHeight = (intImageHeight + (settings.containerBorderSize * 2));
            var intDiffW = intCurrentWidth - intWidth;
            var intDiffH = intCurrentHeight - intHeight;
            objects.imageBox.animate({
                width: intWidth,
                height: intHeight
            }, settings.containerResizeSpeed, function () {
                _show_image();
                $(this).height('auto');
            });
            if ((intDiffW == 0) && (intDiffH == 0)) {
                if ($.browser.msie) {
                    ___pause(250);
                }
                else {
                    ___pause(100);
                }
            }
            objects.dataBox.css({
                width: intImageWidth
            });
            objects.btnNext.add(objects.btnPrev).css({
                height: intImageHeight + (settings.containerBorderSize * 2)
            });
        }
        function _show_image() {
            objects.loading.hide();
            if (settings.hideImage) {
                _show_image_data();
                _set_navigation();
            }
            else {
                objects.image.fadeIn(function () {
                    _show_image_data();
                    _set_navigation();
                });
            }
            _preload_neighbor_images();
        }
        function _show_image_data() {
            objects.dataBox.slideDown("fast");
            objects.caption.hide();
            if (!settings.noTitle && settings.imageArray[settings.activeImage].title) {
                objects.caption.html(settings.imageArray[settings.activeImage].title).show();
            }
            if (settings.imageArray.length > 1) {
                objects.current.html(settings.txtImage + " " + (settings.activeImage + 1) + " " + settings.txtOf + " " + settings.imageArray.length).show();
            }
        }
        function _set_navigation() {
            if (settings.hideNavigator) return;
            objects.navigator.show();
            objects.btnPrev.add(objects.btnNext).css({
                background: "transparent url(" + settings.imageBlank + ") no-repeat"
            });
            if (settings.activeImage != 0) {
                if (settings.fixedNavigation) {
                    objects.btnNext.css({
                        background: "url(" + settings.imageBtnPrev + ") left 15% no-repeat"
                    }).unbind().bind("click", function () {
                        settings.activeImage = settings.activeImage - 1;
                        _set_image_to_view();
                        return false;
                    });
                }
                else {
                    objects.btnPrev.unbind().hover(function () {
                        $(this).css({
                            background: "url(" + settings.imageBtnPrev + ") left 15% no-repeat"
                        });
                    }, function () {
                        $(this).css({
                            background: "transparent url(" + settings.imageBlank + ") no-repeat"
                        });
                    }).show().bind("click", function () {
                        settings.activeImage = settings.activeImage - 1;
                        _set_image_to_view();
                        return false;
                    });
                }
            }
            if (settings.activeImage != (settings.imageArray.length - 1)) {
                if (settings.fixedNavigation) {
                    objects.btnNext.css({
                        background: "url(" + settings.imageBtnNext + ") right 15% no-repeat"
                    }).unbind().bind("click", function () {
                        settings.activeImage = settings.activeImage + 1;
                        _set_image_to_view();
                        return false;
                    });
                }
                else {
                    objects.btnNext.unbind().hover(function () {
                        $(this).css({
                            background: "url(" + settings.imageBtnNext + ") right 15% no-repeat"
                        });
                    }, function () {
                        $(this).css({
                            background: "transparent url(" + settings.imageBlank + ") no-repeat"
                        });
                    }).show().bind("click", function () {
                        settings.activeImage = settings.activeImage + 1;
                        _set_image_to_view();
                        return false;
                    });
                }
            }
            if (!settings.shortcutDisabled) _enable_keyboard_navigation();
        }
        function _enable_keyboard_navigation() {
            $(document).keydown(function (objEvent) {
                _keyboard_action(objEvent);
            });
        }
        function _disable_keyboard_navigation() {
            $(document).unbind();
        }
        function _keyboard_action(objEvent) {
            if (objEvent == null) {
                keycode = event.keyCode;
                escapeKey = 27;
            }
            else {
                keycode = objEvent.keyCode;
                escapeKey = objEvent.DOM_VK_ESCAPE;
            }
            key = String.fromCharCode(keycode).toLowerCase();
            if ((key == settings.keyToClose) || (key == "x") || (keycode == escapeKey)) {
                _finish();
            }
            if ((key == settings.keyToPrev) || (keycode == 37)) {
                if (settings.activeImage != 0) {
                    settings.activeImage = settings.activeImage - 1;
                    _set_image_to_view();
                    _disable_keyboard_navigation();
                }
            }
            if ((key == settings.keyToNext) || (keycode == 39)) {
                if (settings.activeImage != (settings.imageArray.length - 1)) {
                    settings.activeImage = settings.activeImage + 1;
                    _set_image_to_view();
                    _disable_keyboard_navigation();
                }
            }
        }
        function _preload_neighbor_images() {
            if ((settings.imageArray.length - 1) > settings.activeImage) {
                objNext = new Image();
                objNext.src = settings.imageArray[settings.activeImage + 1].href;
            }
            if (settings.activeImage > 0) {
                objPrev = new Image();
                objPrev.src = settings.imageArray[settings.activeImage - 1].href;
            }
        }

        function _disposeElements() {
            objects.mainBox.remove();
            objects.overlay.fadeOut(function () {
                objects.overlay.remove();
                objects.container.remove();
            });
            $("embed, object, select").css({
                visibility: "visible"
            });
        }

        function _finish() {
            if (finishHandlers.length) {
                for (var i = 0; i < finishHandlers.length; i++) {
                    try {
                        finishHandlers[i]();
                    }
                    catch (ex) {
                        if (window.console) console.log(ex);
                    }
                }
            }

            _disposeElements();

            _unregisterClose();
        }
        function ___getPageSize() {
            var xScroll, yScroll;
            if (window.innerHeight && window.scrollMaxY) {
                xScroll = window.innerWidth + window.scrollMaxX;
                yScroll = window.innerHeight + window.scrollMaxY;
            }
            else {
                if (document.body.scrollHeight > document.body.offsetHeight) {
                    xScroll = document.body.scrollWidth;
                    yScroll = document.body.scrollHeight;
                }
                else {
                    xScroll = document.body.offsetWidth;
                    yScroll = document.body.offsetHeight;
                }
            }
            var windowWidth, windowHeight;
            if (self.innerHeight) {
                if (document.documentElement.clientWidth) {
                    windowWidth = document.documentElement.clientWidth;
                }
                else {
                    windowWidth = self.innerWidth;
                }
                windowHeight = self.innerHeight;
            }
            else {
                if (document.documentElement && document.documentElement.clientHeight) {
                    windowWidth = document.documentElement.clientWidth;
                    windowHeight = document.documentElement.clientHeight;
                }
                else {
                    if (document.body) {
                        windowWidth = document.body.clientWidth;
                        windowHeight = document.body.clientHeight;
                    }
                }
            }
            if (yScroll < windowHeight) {
                pageHeight = windowHeight;
            }
            else {
                pageHeight = yScroll;
            }
            if (xScroll < windowWidth) {
                pageWidth = xScroll;
            }
            else {
                pageWidth = windowWidth;
            }
            arrayPageSize = new Array(pageWidth, pageHeight, windowWidth, windowHeight);
            return arrayPageSize;
        }
        function ___getPageScroll() {
            var xScroll, yScroll;
            if (self.pageYOffset) {
                yScroll = self.pageYOffset;
                xScroll = self.pageXOffset;
            }
            else {
                if (document.documentElement && document.documentElement.scrollTop) {
                    yScroll = document.documentElement.scrollTop;
                    xScroll = document.documentElement.scrollLeft;
                }
                else {
                    if (document.body) {
                        yScroll = document.body.scrollTop;
                        xScroll = document.body.scrollLeft;
                    }
                }
            }
            arrayPageScroll = new Array(xScroll, yScroll);
            return arrayPageScroll;
        }
        function ___pause(ms) {
            var date = new Date();
            curDate = null;
            do {
                var curDate = new Date();
            }
            while (curDate - date < ms);
        }
        var matchedNodes = $(selector);
        var top = matchedNodes[0];
        var lightBoxImages = matchedNodes.attr("lightbox-images");
        if (lightBoxImages) {
            lightBoxImages = lightBoxImages.toString();
            if (lightBoxImages.indexOf("EVAL:") == 0) {
                var func = eval("(function(){" + lightBoxImages + "})");
                matchedNodes = func.call(top);
            }
            else {
                if (lightBoxImages.indexOf("URL:") == 0) {
                    var oldRequest = cachedRequestContents[lightBoxImages];
                    if (oldRequest && (new Date().getTime() - oldRequest.time) > 1000 * 60) {
                        _initialize($(oldRequest.node).children());
                    }
                    else {
                        $.get(lightBoxImages.substr(4), null, function (data) {
                            var div = document.createElement("DIV");
                            cachedRequestContents[lightBoxImages] = {
                                data: data,
                                time: new Date().getTime(),
                                node: div
                            };
                            $(div).html(data);
                            _initialize($(div).children());
                        });
                    }
                }
                else {
                    matchedNodes = $(top).find(lightBoxImages);
                    if (event) {
                        var target = event.target || event.srcElement;
                        while (target) {
                            if ($(target).is(lightBoxImages)) {
                                break;
                            }
                            target = target.parentNode;
                        }
                        if (target) {
                            _initialize(matchedNodes, target);
                        }
                    }
                    else {
                        _initialize(matchedNodes);
                    }
                }
            }
        }
        else {
            var rel = matchedNodes.attr("rel");
            if (rel) {
                _initialize($("[rel=" + rel + "]"), top);
            }
            else {
                _initialize($(top));
            }
        }
        return false;
    };
}
__lightBox(jQuery);